/*
 * _1w.c
 *
 * Created: 11.02.2013 11:39:26
 *  Author: saenko
 */ 
#include <avr/io.h>


F_CPU = 8000000;

#include <avr/delay.h>

#define cbi(reg,bit)	reg &= ~(_BV(bit))
#define sbi(reg,bit)	reg |= (_BV(bit))

#define ON_TIMER_INT sbi(TIMSK0,TOIE0)
#define OFF_TIMER_INT cbi(TIMSK0,TOIE0)

#define SET_OW_OUT sbi(PORTD,4)
#define CLR_OW_OUT cbi(PORTD,4)

#define OW_TO_OUT  sbi(DDRD,PD4)
#define OW_TO_IN  cbi(DDRD,PD4)

void ow_init(void)
{
	sbi(DDRD,PD4);
	
		sbi(DDRD,PD5);
	DDRD = 0xFF;
	SET_OW_OUT;
	//timer0
	TCCR0B = (1<<CS01);
	OFF_TIMER_INT;
	//int0
	
}

unsigned char wait_us(unsigned char data)
{
	TCNT0 = 0;
	while(TCNT0<data)
	{
		asm("nop");
	}
}

unsigned char ow_read(void)
{
	if((PIND&0b00010000)>0) return 1;
	else return 0;
}

unsigned char ow_reset(void)
{
	OW_TO_OUT;
	CLR_OW_OUT;
	wait_us(240);
	wait_us(240);
	SET_OW_OUT;
	OW_TO_IN;
	
	wait_us(60);
	if(ow_read()) return 0;
	else
	{
		wait_us(250);
		wait_us(250);
		 return 1;
	}		 
	
}

void ow_send_one(void)
{
	OW_TO_OUT;
	CLR_OW_OUT;
	wait_us(4);
	SET_OW_OUT;
	OW_TO_IN;	
	wait_us(60);

}

void ow_send_zero(void)
{
	OW_TO_OUT;
	CLR_OW_OUT;
	wait_us(63);
	SET_OW_OUT;
	OW_TO_IN;
	wait_us(10);

}

void ow_send_byte(unsigned char data)
{
	for(unsigned char i=0;i<8;i++)
	{
	/*	if((data&0b10000000)>0) ow_send_one();
		else ow_send_zero();*/
	
	if(data&0b00000001) ow_send_one();
	else ow_send_zero();
		
		data = 1>>data;
	}
		wait_us(40);
}

unsigned char ow_read_bit(void)
{
	unsigned char data;
	
	OW_TO_OUT;
	CLR_OW_OUT;
	wait_us(10);
	SET_OW_OUT;
	OW_TO_IN;
	wait_us(20);
	
	data = ow_read();
	wait_us(40);
	
	return data;	
}

unsigned char ow_read_byte(void)
{	
	unsigned char data;
	for(unsigned char i=0;i<64;i++)
	{
		data += ow_read_bit();
		data = data<<1;
	}
	return data;
}